#include <QThread>
#include <QTimer>
#include <QCoreApplication>
#include <QDebug>

// 工作对象类，包含 QTimer
class Worker : public QObject {
    Q_OBJECT
public:
    Worker() {
        timer = new QTimer(this);
        connect(timer, &QTimer::timeout, this, []() {
            qDebug() << "Timer triggered";
        });
        timer->start(1000); // 每秒触发一次
    }

    ~Worker() {
        qDebug() << "Worker destroyed";
    }

public slots:
    void stop() {
        if (timer->isActive()) {
            timer->stop();
            qDebug() << "Timer stopped";
        }
    }

private:
    QTimer *timer;
};

// 自定义线程类
class MyThread : public QThread {
    Q_OBJECT
public:
    explicit MyThread(QObject *parent = nullptr) : QThread(parent) {}

    void run() override {
        qDebug() << "Thread started";
        QThread::exec(); // 启动事件循环
    }

    ~MyThread() {
        qDebug() << "Thread destroyed";
    }
};

int main(int argc, char *argv[]) {
    QCoreApplication app(argc, argv);

    MyThread thread;
    Worker *worker = new Worker();

    // 将 Worker 移动到线程中
    worker->moveToThread(&thread);

    // 启动线程
    thread.start();

    // 模拟退出逻辑
    QTimer::singleShot(5000, &app, [&]() {
        qDebug() << "Stopping the thread";
        
        // 停止 Worker 的 QTimer
        QMetaObject::invokeMethod(worker, "stop", Qt::BlockingQueuedConnection);

        // 退出线程的事件循环
        thread.quit();

        // 等待线程完成退出
        thread.wait();

        // 删除 Worker 和线程对象
        delete worker;
        qDebug() << "Worker deleted";
    });

    return app.exec();
}